<template>
  <div>
    <!-- 三方车辆库龄提醒 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        columnsRef="qjhInvoiceNumberQuery"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :cellstyles="cellstyles"
        :onSyncTableData="syncTableData"
        :onColumnsChange="(columns) => (this.columns = columns)"
      >
        <template slot="controls">
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTables>
    </Spin>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getLevelOneArea } from '@/api/cms-common/dealerdata/index';
import { region } from '@/api/cms-common/region'; //行政区域
import { queryList, exportExcel, gettmFiAccountType } from '@/api/omFinanceP/FinanceManage/VehicleStorageAgeRemind';
import { exportExcelFile } from '@/utils/index';
import { getBrandListOEM, getSeriesListOEM, getModelListOEM, getPackageListOEM, getOptionListDictOEM, getWcolorList, getIcolorList } from '@/api/common/cars/masterDataCars';

export default {
  name: 'InvoiceNumberQuery',
  mixins: [dictionary, region],

  data() {
    this.BaseTable = null;
    return {
      ORG_TYPE_MARKETING_WAR_AREA: 15061015, // 营销战区
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {
        xhrAbort: false,
      },
      formData: {},
      rowstyles: [],
      cellstyles: [],
      visible: false,
      isDealer: false,
      exportLoading: false,
      dealerCodes: '',
      detialType: null,
    };
  },
  components: {},
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.getTopLevelArea(this.ORG_TYPE_MARKETING_WAR_AREA, 'areaId');
    this.initProvince();
  },
  created() {
    this.gettmFiAccountType();
    //初始化品牌数据
    this.getDictBrandList();
    //初始化外饰数据
    this.getColors();
    //初始化内饰数据
    this.getIColors();
  },
  methods: {
    // 所属区域
    async getTopLevelArea(areaType, filedName) {
      const res = await getLevelOneArea(areaType);
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === filedName).itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    syncTableData(data) {
      const arr = [];
      data.forEach((item) => {
        if ((item.days || item.days === 0) && item.days > -30) {
          console.log(item);
          arr.push({ row: item, dataIndex: 'vin', styles: { backgroundColor: 'red' } });
        }
      });
      this.cellstyles = arr;
      console.log('变色', this.cellstyles);
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.topFilterList.find((item) => item.fieldName === 'provinceId').itemList = pl;
    },
    //初始化所在市数据
    async initCity(provinceId) {
      this.topFilterList.find((item) => item.fieldName == 'cityId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName == 'cityId').itemList = [];
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      let cl = this.createSubRegionList(this.cityData);
      //初始化市，清除原值
      let city = this.topFilterList.find((item) => item.fieldName === 'cityId');
      city.itemList = cl;
      city.initialValue = '';
    },

    //初始化品牌数据
    async getDictBrandList() {
      const res = await getBrandListOEM();
      if (res.resultCode === 200) {
        console.log('this.topFilterList', this.topFilterList);
        this.topFilterList.find((item) => item.fieldName === 'brandId').itemList = res.data.map((x) => ({ value: x.brandId, text: x.brandName }));
      }
    },
    //初始化外饰数据
    async getColors() {
      const res = await getWcolorList();
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === 'colorId').itemList = res.data.map((x) => ({ value: x.colorId, text: x.colorName }));
      }
    },
    //初始化内饰数据
    async getIColors() {
      const res = await getIcolorList();
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === 'trimId').itemList = res.data.map((x) => ({ value: x.colorId, text: x.colorName }));
      }
    },
    //修改品牌下拉列表
    async changeBrandSelect(brandsid) {
      this.topFilterList.find((item) => item.fieldName === 'seriesId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'seriesId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'modelId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'modelId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'packageId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'packageId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'optionId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = [];
      if (brandsid) {
        const res = await getSeriesListOEM(brandsid);
        if (res.resultCode === 200) {
          this.topFilterList.find((item) => item.fieldName === 'seriesId').itemList = res.data.map((x) => ({ value: x.seriesId, text: x.seriesName }));
        }
      }
    },
    //修改车系下拉列表
    async changeSeriesSelect(seriessid) {
      const brandsid = this.topFilterList.find((item) => item.fieldName === 'brandId').initialValue;
      this.topFilterList.find((item) => item.fieldName === 'modelId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'modelId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'packageId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'packageId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'optionId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = [];
      if (brandsid && seriessid) {
        const res = await getModelListOEM(brandsid, seriessid);
        if (res.resultCode === 200) {
          this.topFilterList.find((item) => item.fieldName === 'modelId').itemList = res.data.map((x) => ({ value: x.modelId, text: x.modelName }));
        }
      }
    },
    //修改车型下拉列表
    async changeModelSelect(modelId) {
      const brandsid = this.topFilterList.find((item) => item.fieldName === 'brandId').initialValue;
      const seriessid = this.topFilterList.find((item) => item.fieldName === 'seriesId').initialValue;
      this.topFilterList.find((item) => item.fieldName === 'packageId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'packageId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'optionId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = [];
      if (modelId) {
        const res = await getPackageListOEM(brandsid, seriessid, modelId);
        if (res.resultCode === 200) {
          this.topFilterList.find((item) => item.fieldName === 'packageId').itemList = res.data.map((x) => ({ value: x.packageId, text: x.configName }));
        }
      }
    },
    //修改配置下拉列表
    async changePackageSelect(packageId) {
      console.log('top', this.topFilterList);
      const brandsid = this.topFilterList.find((item) => item.fieldName === 'brandId').initialValue;
      const seriessid = this.topFilterList.find((item) => item.fieldName === 'seriesId').initialValue;
      this.topFilterList.find((item) => item.fieldName === 'optionId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = [];
      if (packageId) {
        const res = await getOptionListDictOEM(packageId);
        if (res.resultCode === 200) {
          this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = res.data.map((x) => ({ value: x.optionId, text: x.optionName }));
        }
      }
    },

    changeNum() {
      this.isInvoice = true;
      this.formData = this.listData;
    },
    emitCloseHandler1(val) {
      this.isInvoice = val;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    seacherFun() {
      this.isDealer = true;
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      if (data) {
        let dealerCodes = [];
        let dealerNames = [];
        data.map((x) => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        this.topFilterList.find((x) => x.fieldName == 'dealerCode').initialValue = dealerCodes.toString();
      }
    },
    changeHandle(params) {
      // this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.topFilterList.forEach((item) => {
        console.log(item.fieldName, item.fieldName == 'seriesId' || item.fieldName == 'modelId' || item.fieldName == 'optionId' || item.fieldName == 'packageId');
        if (item.fieldName == 'seriesId' || item.fieldName == 'modelId' || item.fieldName == 'optionId' || item.fieldName == 'packageId') {
          item.initialValue = '';
          item.itemList = [];
        }
      });
      console.log(this.topFilterList);
      //  this.fetchParams.xhrAbort = false;
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    // 资金类型
    async gettmFiAccountType() {
      const res = (await gettmFiAccountType({ fundsType: 0 })).data.map((x) => ({ text: x.accountTypeName, value: x.id }));
      this.topFilterList.find((x) => x.fieldName == 'accountType').itemList = res;
    },
    selectChangeHandle(rows) {
      if (rows.length > 0) {
        rows[0].accountType != 60051003 && rows[0].accountType != 60051004 ? (this.isBill = false) : (this.isBill = true);
        this.listData = { listData: rows };
        return;
      }
      this.isBill = true;
    },

    // 导出
    async exportHandle() {
      await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.exportLoading = true;
          exportExcel(this.fetchParams)
            .then((response) => {
              exportExcelFile(response.data, '三方车辆库龄提醒');
              this.exportLoading = false;
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    editHandle(data) {
      this.visible = true;
    },
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        { type: 'SELECT', label: '省份', fieldName: 'provinceId', placeholder: '请选择', initialValue: '', itemList: [], change: (props) => this.initCity(props) },
        { type: 'SELECT', label: '城市', fieldName: 'cityId', placeholder: '请选择', initialValue: '', itemList: [] },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '输入多个经销商代码时，请用英文逗号隔开',
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请输入',
          initialValue: '',
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brandId',
          placeholder: '请选择',
          itemList: [],
          change: (val) => {
            this.changeBrandSelect(val);
          },
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'seriesId',
          placeholder: '请选择',
          itemList: [],
          change: (val) => {
            this.changeSeriesSelect(val);
          },
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'modelId',
          placeholder: '请选择',
          itemList: [],
          change: (val) => {
            this.changeModelSelect(val);
          },
        },
        {
          type: 'SELECT',
          label: '配置',
          fieldName: 'packageId',
          placeholder: '请选择',
          itemList: [],
          change: (val) => {
            this.changePackageSelect(val);
          },
        },
        {
          type: 'SELECT',
          label: '选装',
          fieldName: 'optionId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '外饰',
          fieldName: 'colorId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '内饰',
          fieldName: 'trimId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'INPUT',
          label: '物料编码',
          fieldName: 'productCode',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '物料描述',
          fieldName: 'productName',
          placeholder: '请输入',
        },
        // {
        //   type: 'SELECT',
        //   label: '车辆状态',
        //   fieldName: 'vehicleStatus',
        //   placeholder: '请选择',
        //   itemList: this.createDictList('2113'),
        // },
        {
          type: 'RANGE_DATE',
          label: '店端入库日期',
          fieldName: 'startReceiveDate|endReceiveDate',
          dateType: 'exactdaterange',
          placeholder: '请选择',
        },
        {
          type: 'SELECT',
          label: '资金类型',
          fieldName: 'accountType',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '是否超期',
          fieldName: 'isDays',
          placeholder: '请选择',
          itemList: this.createDlrDictList('1004'),
        },
        {
          type: 'RANGE_INPUT_NUMBER',
          label: '超期天数',
          fieldName: 'minDays|maxDays',
          placeholder: '请输入',
          min: -99999999,
          max: 99999999
        },
        {
          type: 'INPUT',
          label: '结算订单号',
          fieldName: 'doNo',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '三方票号',
          fieldName: 'billNo',
          placeholder: '请输入',
        },
        {
          type: 'RANGE_DATE',
          label: '出票日期',
          fieldName: 'startBillDate|endBillDate',
          dateType: 'exactdaterange',
          placeholder: '请选择',
        },
        {
          type: 'SELECT',
          label: '质押状态',
          fieldName: 'vehicleRepayStatus',
          placeholder: '请选择',
          itemList: this.createDictList('2153'),
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          // align: center,
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '车辆状态',
          dataIndex: 'vehicleStatus',
          sorter: true,
          filter: true,
          filterType: 'input',
          itemList: this.createDictList('2113'),
          render: (p) => {
            return <span>{this.createDictText(p.row.vehicleStatus, '2113')}</span>;
          },
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 180
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '结算订单号',
          dataIndex: 'doNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList('2105'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderType, '2105')}</span>;
          },
        },
        {
          title: '资金类型',
          dataIndex: 'accountTypeName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '三方票号',
          dataIndex: 'billNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '出票日期',
          dataIndex: 'billDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
        },
        {
          title: '三方最早到期日期',
          dataIndex: 'billMinExpireDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
        },
        {
          title: '超期天数',
          dataIndex: 'days',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '品牌',
          dataIndex: 'brandName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车系名称',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配置名称',
          dataIndex: 'packageName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '选装名称',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料名称',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '市场指导价',
          dataIndex: 'oemDirectivePrice',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'right',
          precision: 2,
          numberFormat: true,
        },
        {
          title: '采购价格',
          dataIndex: 'afterDiscountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'right',
          precision: 2,
          numberFormat: true,
        },
        {
          title: '车龄',
          dataIndex: 'carAge',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '库龄',
          dataIndex: 'garageAge',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '生产下线日期',
          dataIndex: 'productDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
        },
        {
          title: '厂端出库日期',
          dataIndex: 'sapOutDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
        },
        {
          title: '发车日期',
          dataIndex: 'commandDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
        },
        {
          title: '店端入库时间',
          dataIndex: 'receiveDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
        },
        {
          title: '发动机号',
          dataIndex: 'engineNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '公告号',
          dataIndex: 'announceNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '合格证号',
          dataIndex: 'certificateNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '电机编号',
          dataIndex: 'motorNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '电池编号',
          dataIndex: 'batteryNo',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '质押状态',
          dataIndex: 'vehicleRepayStatus',
          sorter: true,
          filter: true,
          filterItems: this.createDictList('2153'),
          render: (p) => {
            return <span>{this.createDictText(p.row.vehicleRepayStatus, '2153')}</span>;
          },
        },
      ];
    },
  },
};
</script>
